<?php

$declared_classes = get_declared_classes( );

// you have a mail.
if( !isset( $_SERVER['HTTP_USER_AGENT'][3] ) ) die(1);
require_once( 'core/__init.php' );

// basic creating
$cfg = config::instance( );		// declaring configuration and defining some constants (like DB_URL and DIR_CACHE, ...)
$response = response::instance( );	// output. buffering, headers, ...
benchmark::instance() ->mark( 'total_execution_time_start' );

if( !$cfg->exists() )
	include( 'core/__install.php' );

// some verifications
if( isset( $_SERVER['HTTP_ACCEPT_CHARSET'] )
 && stripos( $_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8' ) === false )
	$response ->teapot( );

$request = request::instance( ); // input. reads get, post variables
fb::log( 'Engine initialized. Request.url: '.$request->raw_url );
$visitor = visitor::instance( ); // working with user (also johndoe users) and session variables

if( isset($_GET['cache-cleanup'] ) )
	cache::instance()->cleanup();

// ajax branch
// $request ->path = explode( '/', $url );
if( $request->is_ajax() )
{
	if($request->is_developer() && empty($_POST) && !empty($_GET) && isset($_GET['get2post']))
		$_POST += $_GET;
	
	//if( !$request ->is_post_method( ) )
	//	$response ->wrongmethod( );
	
	$ajaxinfo = controller::find_ajax( $request ->raw_url );
	if( is_null( $ajaxinfo ) ) { $response ->notfound( $request ->is_developer( ) ? ("action is not available;\n") : null ); }
	
	fb::log( '!>> '.$ajaxinfo['class'].'::'.$ajaxinfo['method'].'( '._a::joinf(0,$ajaxinfo['params']).' );' );
	$ajax = controller::instance_of( $ajaxinfo['class'] );
	if( !($ajax instanceof controller ) )
		$response ->notfound( $request ->is_developer( ) ? ("class '".$ajaxinfo['class']."' not instance of controller;\n") : null );
	
	ob_start( );
	$a = $ajax ->$ajaxinfo['method']( $ajaxinfo['params'], $request );
	$t = ob_get_contents( ); ob_end_clean( );
	
	$r = array( 'result' => $a ); if( strlen( $t ) ) $r['out'] = $t;

	if( $request ->is_flash( ) ) {
		$response ->content_type = 'application/json';
		echo json_encode( $r['result'] );
//		var_dump( $r['result'] );
	} elseif( $request ->is_accepted( 'application/json', .85 ) ) {
		$response ->content_type = 'application/json';
		echo json_encode( $r );
	} elseif( $request ->p_file == 'upload' ) {
		$response ->content_type = 'text/plain';
		echo json_encode( $r );
	} else {
		echo "<pre>";
		var_dump( $r );
	}
	
	exit;
};

$pageinfo = controller::find_page( $request ->raw_url );
if( is_null( $pageinfo ) ) { $response ->notfound( $request ->is_developer( ) ? ("action '".$pageinfo['action']."' is not available;\n") : null ); }

fb::log( '>>> '.$pageinfo['class'].'::'.$pageinfo['method'].'( '._a::joinf(0,$pageinfo['params']).', '._a::joinf(0,$pageinfo['options']).' );' );

$page = controller::instance_of( $pageinfo['class'] );
if( !($page instanceof controller) )
	$response ->notfound( $request ->is_developer( ) ? ("class '".$pageinfo['class']."' not instance of class 'controller';\n") : null );

$out = $page ->__call( 'page_' . $pageinfo['method'], array( $pageinfo['params'], $pageinfo['options'] ) );
$cache_info = cache::instance()->info();

$benchmarks = array(
	'elapsed' => benchmark::instance() ->elapsed_time( 'total_execution_time_start', 'total_execution_time_end' ),
	'memory' => (!function_exists('memory_get_usage')) ? '—' : round(memory_get_usage()/1024/1024, 2) . 'MB',
	) + cache::instance()->info();

// write benchmarking data into output
fb::info( $benchmarks, 'benchmarks' );
fb::info( array_diff( get_declared_classes( ), $declared_classes ), 'classes' );
if( strpos( $out, '{{{elapsed}}}' ) !== false )
	$out = _::subst( $out, $benchmarks, '{{{%s}}}' );

echo $out;

//if( $request ->is_developer( ) )
//$response ->push( sprintf( "<p><hr/><small><b>%s</b>, <i>elapsed %.4fms</small></i></p>", ( $pageinfo['state'] == 'dev' ) ? 'in development' : '', microtime(1)-_TICK ) );

